package com.work.demo.utils;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @ClassName : AESUtil
 * @Description : AES加解密工具类
 * @Author : LinYa
 * @Date: 2022/5/25  14:04
 */
public class AESUtil {

	/**
	 * 使用aes-128-gcm 方式加密
	 * @param key 密钥类
	 * @param data 要加密的数据
	 * @return 加密后的数据
	 */
	public static byte[] encrypt(byte[] key, byte[] data) {
		try {
			KeyGenerator aes = KeyGenerator.getInstance("AES");
			aes.init(128, new SecureRandom(key));
			//生成随机密钥
			SecretKey secretKey = aes.generateKey();
			Cipher cipher = Cipher.getInstance("AES");
			//加密
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			return cipher.doFinal(data);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 使用aes-128-gcm 方式解密
	 * @param key 密钥类
	 * @param data 要解密的数据
	 * @return 解密后的数据
	 */
	public static byte[] decrypt(byte[] key, byte[] data) {
		try {
			KeyGenerator aes = KeyGenerator.getInstance("AES");
			aes.init(128, new SecureRandom(key));
			//生成随机密钥
			SecretKey secretKey = aes.generateKey();
			Cipher cipher = Cipher.getInstance("AES");
			//解密
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			return cipher.doFinal(data);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		return null;
	}
}
